{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d1ff97f3",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "<table style=\"margin: 0; text-align: left; width:100%\">\n",
    "    <tr>\n",
    "        <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n",
    "        </td>\n",
    "        <td>\n",
    "            <h2 style=\"color:#ff7800;\">Important point - please read</h2>\n",
    "            <span style=\"color:#ff7800;\">This is the experiment to analyze the stocks based on the Benjamin Graham's The Intelligent Investor. This tool Analyze any stock symbol from the NSE (National Stock Exchange) or BSE (Bombay Stock Exchange) \n",
    "This is just the learning purpose and no investment advice should be taken from this.\n",
    "            </span>\n",
    "        </td>\n",
    "    </tr>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3f99eb40",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c0943f71",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "load_dotenv(override=True)\n",
    "\n",
    "!uv add yfinance pandas\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b86f232b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install dependencies (only needed once in your env)\n",
    "!uv add yfinance pandas\n",
    "\n",
    "# Import them\n",
    "import yfinance as yf\n",
    "import pandas as pd\n",
    "\n",
    "from IPython.display import Markdown, display"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "09368124",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Example: Reliance Industries on NSE\n",
    "stock_symbol = \"TCS.NS\"  # You can change to TCS.NS, INFY.NS, etc."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "410494b4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# LLM client setup (OpenAI + Groq via OpenAI-compatible API)\n",
    "import os\n",
    "from dotenv import load_dotenv\n",
    "from openai import OpenAI\n",
    "\n",
    "load_dotenv(override=True)\n",
    "\n",
    "OPENAI_API_KEY = os.getenv(\"OPENAI_API_KEY\")\n",
    "GROQ_API_KEY = os.getenv(\"GROQ_API_KEY\")\n",
    "\n",
    "openai_client = OpenAI(api_key=OPENAI_API_KEY) if OPENAI_API_KEY else None\n",
    "# Groq uses OpenAI-compatible endpoint|\n",
    "GROQ_BASE_URL = \"https://api.groq.com/openai/v1\"\n",
    "groq_client = OpenAI(api_key=GROQ_API_KEY, base_url=GROQ_BASE_URL) if GROQ_API_KEY else None\n",
    "\n",
    "print(\n",
    "    f\"OpenAI: {'ON' if openai_client else 'OFF'} | Groq: {'ON' if groq_client else 'OFF'}\"\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a5c38c6f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Helper: compute Benjamin Graham-style checks (simplified for public data)\n",
    "# Note: True Graham analysis needs per-share earnings for multi-year periods and balance-sheet figures.\n",
    "# We use yfinance fields as proxies and document assumptions.\n",
    "import numpy as np\n",
    "\n",
    "\n",
    "def compute_graham_checks(ticker: str):\n",
    "    T = yf.Ticker(ticker)\n",
    "\n",
    "    # Price and trailing PE proxy\n",
    "    info = T.info if hasattr(T, \"info\") else {}\n",
    "    current_price = info.get(\"currentPrice\")\n",
    "    trailing_pe = info.get(\"trailingPE\")\n",
    "    forward_pe = info.get(\"forwardPE\")\n",
    "    peg_ratio = info.get(\"pegRatio\")\n",
    "    dividend_yield = info.get(\"dividendYield\")  # fraction\n",
    "    roe = info.get(\"returnOnEquity\")  # fraction\n",
    "    debt_to_equity = info.get(\"debtToEquity\")  # percent\n",
    "    current_ratio = info.get(\"currentRatio\")\n",
    "    book_value = info.get(\"bookValue\")  # per share\n",
    "    price_to_book = info.get(\"priceToBook\")\n",
    "    profit_margins = info.get(\"profitMargins\")  # fraction\n",
    "\n",
    "    # Conservative thresholds inspired by Graham (adjusted, simplified):\n",
    "    # - PE <= 15 (or <= 20 if growth)  \n",
    "    # - PB <= 1.5 (or PE*PB <= 22.5)  \n",
    "    # - Dividend present preferred  \n",
    "    # - Current ratio >= 1.5 for industrials (approx)  \n",
    "    # - D/E <= 1 (approx)  \n",
    "    # - Stable profitability (we proxy using positive margin and ROE)\n",
    "\n",
    "    pe_ok = trailing_pe is not None and trailing_pe <= 15\n",
    "    pb_ok = price_to_book is not None and price_to_book <= 1.5\n",
    "\n",
    "    combo_ok = False\n",
    "    if (trailing_pe is not None) and (price_to_book is not None):\n",
    "        combo_ok = (trailing_pe * price_to_book) <= 22.5\n",
    "\n",
    "    de_ok = (debt_to_equity is not None) and (debt_to_equity <= 100)  # percent\n",
    "    cr_ok = (current_ratio is not None) and (current_ratio >= 1.5)\n",
    "    div_ok = (dividend_yield is not None) and (dividend_yield > 0)\n",
    "    profitability_ok = (\n",
    "        (profit_margins is not None and profit_margins > 0)\n",
    "        and (roe is not None and roe > 0)\n",
    "    )\n",
    "\n",
    "    checks = {\n",
    "        \"price\": current_price,\n",
    "        \"trailing_pe\": trailing_pe,\n",
    "        \"price_to_book\": price_to_book,\n",
    "        \"pe_ok\": pe_ok,\n",
    "        \"pb_ok\": pb_ok,\n",
    "        \"pe_x_pb_ok\": combo_ok,\n",
    "        \"dividend_yield\": dividend_yield,\n",
    "        \"dividend_ok\": div_ok,\n",
    "        \"debt_to_equity_pct\": debt_to_equity,\n",
    "        \"debt_to_equity_ok\": de_ok,\n",
    "        \"current_ratio\": current_ratio,\n",
    "        \"current_ratio_ok\": cr_ok,\n",
    "        \"profit_margins\": profit_margins,\n",
    "        \"roe\": roe,\n",
    "        \"profitability_ok\": profitability_ok,\n",
    "    }\n",
    "\n",
    "    total_pass = sum(\n",
    "        1\n",
    "        for k in [\n",
    "            \"pe_ok\",\n",
    "            \"pb_ok\",\n",
    "            \"pe_x_pb_ok\",\n",
    "            \"dividend_ok\",\n",
    "            \"debt_to_equity_ok\",\n",
    "            \"current_ratio_ok\",\n",
    "            \"profitability_ok\",\n",
    "        ]\n",
    "        if checks[k]\n",
    "    )\n",
    "    checks[\"passes\"] = total_pass\n",
    "    checks[\"total_criteria\"] = 7\n",
    "    return checks\n",
    "\n",
    "\n",
    "def format_checks_md(ticker: str, checks: dict) -> str:\n",
    "    yn = lambda b: \"✅\" if b else \"❌\"\n",
    "    lines = [f\"### Graham-style screen for `{ticker}`\"]\n",
    "    lines.append(\"- Price: \" + str(checks.get(\"price\")))\n",
    "    lines.append(\n",
    "        f\"- PE: {checks.get('trailing_pe')} | PB: {checks.get('price_to_book')} | PE×PB<=22.5: {yn(checks.get('pe_x_pb_ok'))}\"\n",
    "    )\n",
    "    lines.append(f\"- PE<=15: {yn(checks.get('pe_ok'))}\")\n",
    "    lines.append(f\"- PB<=1.5: {yn(checks.get('pb_ok'))}\")\n",
    "    lines.append(\n",
    "        f\"- Dividend yield: {checks.get('dividend_yield')} | Present: {yn(checks.get('dividend_ok'))}\"\n",
    "    )\n",
    "    lines.append(\n",
    "        f\"- D/E%: {checks.get('debt_to_equity_pct')} | <=100%: {yn(checks.get('debt_to_equity_ok'))}\"\n",
    "    )\n",
    "    lines.append(\n",
    "        f\"- Current ratio: {checks.get('current_ratio')} | >=1.5: {yn(checks.get('current_ratio_ok'))}\"\n",
    "    )\n",
    "    lines.append(\n",
    "        f\"- Profit margin: {checks.get('profit_margins')} | ROE: {checks.get('roe')} | Positive: {yn(checks.get('profitability_ok'))}\"\n",
    "    )\n",
    "    lines.append(\n",
    "        f\"- Score: {checks.get('passes')}/{checks.get('total_criteria')} criteria passed\"\n",
    "    )\n",
    "    return \"\\n\".join(lines)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7b1068f3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run metrics and display\n",
    "checks = compute_graham_checks(stock_symbol)\n",
    "display(Markdown(format_checks_md(stock_symbol, checks)))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e57d502a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# LLM analysis using available provider(s)\n",
    "\n",
    "def analyze_with_llm(summary_markdown: str, provider: str = \"auto\",\n",
    "                      openai_model: str = \"gpt-4o-mini\",\n",
    "                      groq_model: str = \"llama-3.3-70b-versatile\") -> str:\n",
    "    sys_msg = (\n",
    "        \"You are a conservative value-investing analyst using Benjamin Graham principles. \"\n",
    "        \"Explain clearly which checks passed/failed, what that implies, and caveats about proxies. \"\n",
    "        \"Be concise and avoid recommendations; this is educational only.\"\n",
    "    )\n",
    "    user_msg = (\n",
    "        \"Analyze the following Graham-style checklist for a stock. \"\n",
    "        \"Summarize pass/fail, key drivers, and a short risk note.\\n\\n\" + summary_markdown\n",
    "    )\n",
    "\n",
    "    def chat(client, model):\n",
    "        resp = client.chat.completions.create(\n",
    "            model=model,\n",
    "            messages=[\n",
    "                {\"role\": \"system\", \"content\": sys_msg},\n",
    "                {\"role\": \"user\", \"content\": user_msg},\n",
    "            ],\n",
    "            temperature=0.4,\n",
    "            max_tokens=400,\n",
    "        )\n",
    "        return resp.choices[0].message.content\n",
    "\n",
    "    outputs = []\n",
    "    if provider in (\"auto\", \"openai\") and openai_client:\n",
    "        try:\n",
    "            outputs.append((\"OpenAI\", chat(openai_client, openai_model)))\n",
    "        except Exception as e:\n",
    "            outputs.append((\"OpenAI\", f\"Error: {e}\"))\n",
    "\n",
    "    if provider in (\"auto\", \"groq\") and groq_client:\n",
    "        try:\n",
    "            outputs.append((\"Groq\", chat(groq_client, groq_model)))\n",
    "        except Exception as e:\n",
    "            outputs.append((\"Groq\", f\"Error: {e}\"))\n",
    "\n",
    "    if not outputs:\n",
    "        return \"No LLM providers available. Set OPENAI_API_KEY and/or GROQ_API_KEY.\"\n",
    "\n",
    "    merged = []\n",
    "    for name, out in outputs:\n",
    "        merged.append(f\"### {name} analysis\\n\\n\" + (out or \"\"))\n",
    "    return \"\\n\\n---\\n\\n\".join(merged)\n",
    "\n",
    "analysis = analyze_with_llm(format_checks_md(stock_symbol, checks))\n",
    "display(Markdown(analysis))\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
